package org.jiucheng.magpiebridge.server.aio.proxy.domain;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.List;

import org.jiucheng.magpiebridge.protocol.Message;
import org.jiucheng.magpiebridge.server.aio.ServerAttachment;
import org.jiucheng.magpiebridge.server.aio.ServerWriteNoProxyClientReadCompletionHandler;
import org.jiucheng.magpiebridge.server.aio.proxy.ProxyAttachment;
import org.jiucheng.magpiebridge.server.util.Container;

/**
 * 
 * @author jiucheng
 *
 */
public class OnlyProxyEstablishmentCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, AsynchronousServerSocketChannel>{

	public void completed(AsynchronousSocketChannel result, AsynchronousServerSocketChannel attachment) {
		attachment.accept(attachment, this);
		try {
			SocketAddress socketAddress = result.getRemoteAddress();
			if (socketAddress instanceof InetSocketAddress) {
				String hostName = ((InetSocketAddress) socketAddress).getHostName();
				List<Object> item = Container.DOMAINS.get(hostName);
				if (item != null) {
					ServerAttachment serverAttachment = (ServerAttachment) item.get(0);
					String remote = (String) item.get(1);
			        if (serverAttachment.canWrited()) {
			            Message message = new Message();
			            message.setMagic(Message.MAGIC);
			            message.setType(Message.Type.CONNECT);
			            message.setUri(Container.CLIENTS_ID.incrementAndGet());
			            byte[] data = remote.getBytes();
			            message.setData(data);
			            message.setSize(data.length);
			            ByteBuffer writeBuffer = Message.toByteBuffer(message);
			            
			            ServerAttachment.proxys.put(message.getUri(), new ProxyAttachment(result).setUri(message.getUri()).setServerAttachment(serverAttachment));
			            serverAttachment.getServer().write(writeBuffer, serverAttachment.setWriteBuffer(writeBuffer), new ServerWriteNoProxyClientReadCompletionHandler());
			        }
					return;
				}
			}
			result.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void failed(Throwable exc, AsynchronousServerSocketChannel attachment) {
        System.out.println("only proxy server failed");
	}
}
